package com.hansen.library.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.hansen.library.R;
import com.hansen.library.ui.widget.dialog.LoadingDialog;
import com.hansen.library.utils.FastClickUtils;
import com.hansen.library.utils.LogUtils;

/**
 * Created by han on 2019/6/10 0010.
 */

public abstract class BaseFragment extends Fragment implements View.OnClickListener {
    protected Context mContext;

    private FragmentTransaction mTransaction;

    private LoadingDialog mLoadingDialog;

    private View rootView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if(rootView == null) {
            rootView = inflater.inflate(getResID(), container, false);
        }

        initView(rootView);

        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        view.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    if(getActivity() != null && getActivity().getCurrentFocus() != null) {
                        if(isShouldHideKeyBoard(view,motionEvent)) {
                            hideKeyboard(getActivity().getCurrentFocus().getWindowToken());
                        }
                    }
                }

                return true;
            }
        });
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        listener();
    }

    @Override
    public void onClick(View v) {
        //防止快速点击
        if (FastClickUtils.isFastClick()) {
            return;
        }

        widgetClick(v);
    }

    protected abstract int getResID();

    protected abstract void initView(View mView);

    protected abstract void initData();

    protected abstract void listener();

    protected abstract void widgetClick(View v);

    //判断是否需要隐藏软键盘
    private boolean isShouldHideKeyBoard(View view, MotionEvent ev) {
        if (view != null && (view instanceof EditText)) {
            int[] l = {0, 0};
            view.getLocationInWindow(l);
            int left = l[0];
            int top = l[1];
            int bottom = top + view.getHeight();
            int right = left + view.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
                //点击EditText事件，忽略
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }


    //隐藏软键盘
    public void hideKeyboard(IBinder windowToken) {
        InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        if (im.isActive() && windowToken != null) {
            im.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * fragment management
     */
    public BaseFragment addFragment(BaseFragment mTargetFragment, int mResId) {
        return addFragment(mTargetFragment, mResId, false);
    }

    public BaseFragment addFragment(BaseFragment mTargetFragment, int mResId, boolean needAddToBackStack) {
        if(mTargetFragment == null) {
            return null;
        }

        mTransaction = getChildFragmentManager().beginTransaction();

        mTransaction.add(mResId, mTargetFragment);

        if (needAddToBackStack) {
            mTransaction.addToBackStack(null);
        }

        try {
            mTransaction.commitAllowingStateLoss();
        } catch (Exception e) {
            LogUtils.e("switch fragment exception" + e.getMessage());
        }

        return mTargetFragment;
    }

    public BaseFragment switchFragment(BaseFragment mCurrentFragment, BaseFragment mTargetFragment, int containerViewId) {
        return switchFragment(mCurrentFragment, mTargetFragment, containerViewId, false);
    }

    protected BaseFragment switchFragment(BaseFragment mCurrentFragment, BaseFragment mTargetFragment, int mResId, boolean needAddToBackStack) {
        if (mCurrentFragment == null || mTargetFragment == null || mCurrentFragment == mTargetFragment) {

            return mTargetFragment;
        }

        mTransaction = getChildFragmentManager().beginTransaction();

        if (mTargetFragment.isAdded()) {
            mTransaction.hide(mCurrentFragment).show(mTargetFragment);
        } else {
            mTransaction.hide(mCurrentFragment).add(mResId, mTargetFragment);
        }

        if (needAddToBackStack) {
            mTransaction.addToBackStack(null);
        }

        try {
            mTransaction.commitAllowingStateLoss();
        } catch (Exception e) {
            LogUtils.e("switch fragment exception" + e.getMessage());
        }

        return mTargetFragment;
    }

    //显示加载进度
    protected void showLoadingDialog() {
        showLoadingDialog(R.string.text_waiting_loading);
    }

    //显示加载进度
    protected void showLoadingDialog(@StringRes int resId) {
        showLoadingDialog(getString(resId));
    }

    //显示加载进度
    protected void showLoadingDialog(String res) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(getActivity())
                    .builder()
                    .setCanceledOnTouchOutside(false)
                    .setCanceled(false);
        }

        mLoadingDialog.setTitle(res);

        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    protected void dismissDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        rootView = null;
        mContext = null;
        if(mLoadingDialog != null) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
        super.onDestroy();
    }
}
